﻿
CREATE trigger [dbo].[TRG_InventoryTransactionUpdate]
on [dbo].[tblInventoryTransaction]
for update
as
begin
	set nocount on

	-- If we are inside a data load then just return
	if coalesce(CONTEXT_INFO(), 0) = 0x999
		return

	-- Updates to inventory transactions are only allowed to update the status code.
	if substring(COLUMNS_UPDATED(), 1, 1) & ~4 <> 0 or
		substring(COLUMNS_UPDATED(), 2, 1) & ~17 <> 0 
	begin
		print 'Columns Updates ' + cast(cast(substring(COLUMNS_UPDATED(), 1, 1) as int) as varchar) + ' ' + cast(cast(substring(COLUMNS_UPDATED(), 2, 1) as int) as varchar)
		RAISERROR( 'Updates to tblInventoryTransaction are only allewed to udpate the transaction status code', 18, -1 )
	end

	if exists ( select 1 from inserted T1 join deleted T2 on T1.InventoryTransactionID = T2.InventoryTransactionID
		where T2.InventoryTransactionStatusCode in ( 'C', 'X', 'L' )
			and not ( T1.InventoryTransactionStatusCode = 'L' and T2.InventoryTransactionStatusCode = 'C' )
			and T2.InventoryTransactionStatusCode <> T1.InventoryTransactionStatusCode )
	begin
		RAISERROR( 'Updates to inventory transaction status are not allowed for transactions that are already in the Canceled or Committed state.', 18, -1 )
	end

end
